const app = angular.module("myApp",['ui.bootstrap', 'ui.bootstrap.treeview2']);

const treeViewTemplate = `
<tree-view ng-if="graphTree != null && graphTree.g != null" tree-service="graphTree" node-label="text"></tree-view>
`;

app.controller("reportController",['$scope','$compile','$sce',function($scope,$compile,$sce){
    $scope.toJSON = function (val) {
        return toJSON(val);
    };
    let request = getRequest();
    $scope.faultId = request["faultId"];
    // $scope.featureIds = JSON.parse(request["featureIds"]);
    console.info(request["matchedNodes"]);
    $scope.matchedNodes = JSON.parse(request["matchedNodes"]);
    $scope.unknownNodes = JSON.parse(request["unknownNodes"]);
    $scope.channels = JSON.parse(request["channels"]);
    $scope.timestamp = parseInt(request["timestamp"]);
    $scope.last_timestamp = parseInt(request["last_timestamp"]);

    $scope.sequence = request["reportId"];
    $scope.reasons = [];

    let queryUrl = `start n=node(${$scope.faultId}) match (n)-[*]->(p) return n,p`;
    $scope.faultUrl = $sce.trustAsResourceUrl(`../browser/NeoEmbed.html?query=${encodeURIComponent(queryUrl).replace(/=/g,'%3d')}`);

    $scope.graphTree = new NodeTreeView();
    Graph.loadGraph($scope.faultId,g=>{
        $scope.graph = g;
        let nodesList = [... g.nodes.values()];
        for(let nd of nodesList){
            if($scope.matchedNodes.some(nid=>nid==nd.id)){
                nd.isMatched = true;
            }
            if($scope.unknownNodes.some(nid=>nid==nd.id)){
                nd.unknown = true;
            }
        }
        $scope.fault = nodesList.filter(node=>node.$type=="Fault")[0];
        $scope.features = nodesList.filter(node=>node.$type=='Feature' && node.isMatched);

        $scope.relatedComponents = [];

        $scope.features.forEach((f,index)=>{
            ComponentNode.loadComponentsFrom(f.id,
                (components)=>{
                    let rset = new Set($scope.relatedComponents);
                    components.forEach(c=>rset.add(c.name));
                    $scope.relatedComponents = [...rset];
                    $scope.$apply();
                }
            );
        });
        let matchedOutIds = $scope.features.filter(f=>f.isMatched).map(f=>f.outId).filter(id=>id!=0);
        console.info(matchedOutIds);
        $scope.reasons = nodesList.filter(node=>node.$type=='Reason').sort((a,b)=>a>b);
        $scope.reasons.filter(r=>matchedOutIds.some(id=>id==r.outId)).forEach(r=>r.isMatched=true);

        $scope.gridShowReasons = $scope.reasons.filter(node=>node.outId && node.outId!=0);

        // $scope.graphTree.nodes = [$scope.graph.toJsonTree()];
        $scope.graphTree.g = g;
        console.info($scope.graphTree);
        $scope.graphTree.collapseAll();

        let tp = $compile( treeViewTemplate )( $scope );
        angular.element("#treeDiv").html("").append( tp );

        $scope.$apply();
    });

    $scope.getNow=function () {
        return new Date($scope.timestamp);
    };
//        FaultNode.loadFaults.callbacks.push(()=>$scope.faults=FaultNode.faults);

}]);

app.filter("toTimeSpan",[function() {
    return function(intVal) {
        let ms = intVal % 1000;
        intVal -= ms;
        intVal /= 1000;
        let s = intVal %60;
        intVal -= s;
        intVal /= 60;
        let min = intVal%60;
        intVal -= min;
        intVal /= 60;
        let hour = intVal%24;
        intVal -= hour;
        let day = intVal / 24;
        let f= (x,label) =>x>0?""+x+label:"";
        return f(day,"d")+f(hour,"h")+f(min,"min")+f(s,"s")+f(ms,"ms")
    };
}]);

app.filter('startX', [function() {
    return function(array,size) {
        if(array.length<=size)
            return array.map(x=>x.toFixed(2)).join(",");
        return array.slice(0,2).map(x=>x.toFixed(2)).join(",")+"等"+array.length+"项";
    };
}]);

function getRequest() {
    let url = location.search; //获取url中"?"符后的字串
    let theRequest = {};
    if (url.indexOf("?") !== -1) {
        let str = url.substr(1);
        let strs = str.split("&");
        for(let i = 0; i < strs.length; i ++) {
            theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}